package com.culturalCenter.dataCenter.Utils;

import com.alibaba.fastjson.JSON;
import com.culturalCenter.dataCenter.customEntity.requestParam.RequestDoorTemplate;
import com.culturalCenter.dataCenter.customEntity.requestParam.RequestVisitorInfo;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Date;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * 对接门禁工具类
 *
 * @author ISMC
 * @since 2020/10/15 9:56
 */
public class DoorHttpUtil {

    public static String getSign(String key, Map<String, Object> param) throws Exception {
        String signString = ClassUtil.setConditionString(param) + "key=" + key;
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] md5ValueByteArray = messageDigest.digest(signString.getBytes(StandardCharsets.UTF_8));
        StringBuilder hex = new StringBuilder(md5ValueByteArray.length * 2);
        for (byte b : md5ValueByteArray) {
            if ((b & 0xFF) < 0x10) {
                hex.append("0");
            }
            hex.append(Integer.toHexString(b & 0xFF));
        }
//        BigInteger bigInteger = new BigInteger(1 , md5ValueByteArray);
//        return bigInteger.toString(16).toUpperCase();
        return hex.toString().toUpperCase();
    }

    public static String sendRequestByTemplate(String url, String key, RequestDoorTemplate doorTemplate) throws Exception {
        StringBuffer sb = new StringBuffer();
        Map<String, Object> param = ClassUtil.setConditionMap(doorTemplate);
//            DigestUtils.md5DigestAsHex("".getBytes());
        param.put("sign", getSign(key, param));
/*        url += "?pageIndex=" + pageNum + "&pageSize=" + pageSize + "&timestamp=" + timestamp +
                "&sign" + MD5Util.getMD5Format("pageIndex=" + pageNum + "&pageSize=" + pageSize + "&timestamp=" + timestamp + "&key=" + key);*/
        return getResponse(url, sb, param);
    }

    // POST请求
    public static String getResponse(String url, StringBuffer sb, Map param) throws IOException {
        HttpURLConnection conn;
        URL urlObj = new URL(url);
        conn = (HttpURLConnection) urlObj.openConnection();
        conn.setUseCaches(false);
        conn.setDoOutput(true);
        conn.setDoInput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), StandardCharsets.UTF_8));
        String jsonString = JSON.toJSONString(param);
//        PrintWriter out = new PrintWriter(conn.getOutputStream());
//        out.println(jsonString.getBytes("utf-8"));
        writer.write(jsonString);
        writer.flush();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        String tmpLine;
        while ((tmpLine = reader.readLine()) != null) {
            sb.append(tmpLine);
        }
        conn.disconnect();
        return sb.toString();
    }

    // GET请求
    public static String getResponse(String url, StringBuffer sb) throws IOException {
        HttpURLConnection conn;
        URL urlObj = new URL(url);
        conn = (HttpURLConnection) urlObj.openConnection();
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
        String tmpLine;
        while ((tmpLine = reader.readLine()) != null) {
            sb.append(tmpLine);
        }
        conn.disconnect();
        return sb.toString();
    }

    public static String sendRequest(String url, String key) throws Exception {
        long timestamp = new Date().getTime() / 1000;
        StringBuffer sb = new StringBuffer();
        SortedMap<String, Object> param = new TreeMap<>();
        param.put("timestamp", timestamp);
        param.put("sign", getSign(key, param));
        return getResponse(url, sb, param);
    }

    public static String sendRequestToGetVisitorQrCode(String url, String key, String callerID) throws Exception {
        long timestamp = new Date().getTime() / 1000;
        StringBuffer sb = new StringBuffer();
        SortedMap<String, Object> param = new TreeMap<>();
        param.put("callerId", callerID);
        param.put("timestamp", timestamp);
        param.put("sign", getSign(key, param));
        return getResponse(url, sb, param);
    }

    public static String sendRequestByVisitorInfo(String url, String key, RequestVisitorInfo visitorInfo) throws Exception {

        StringBuffer sb = new StringBuffer();
        Map<String, Object> param = ClassUtil.setConditionMap(visitorInfo);
        param.put("sign", getSign(key, param));
        return getResponse(url, sb, param);
    }

}
